/* eslint-disable @typescript-eslint/no-var-requires */
// eslint-disable-next-line @typescript-eslint/no-var-requires
const webpack = require('webpack')
const webpackConfig = require('@vue/cli-service/webpack.config')
const Router = require('koa-router')
const MemoryFS = require('memory-fs')
const { createBundleRenderer } = require('vue-server-renderer')
const mfs = new MemoryFS()
const fs = require('fs')
const router = new Router()
const path = require('path')
const axios = require('axios')


let bunle;
const webpackCompiler = webpack(webpackConfig)
webpackCompiler.outputFileSystem = mfs
webpackCompiler.watch({}, (err, state) => {
  const bunldePath = path.join(webpackConfig.output.path, 'vue-ssr-server-bundle.json')
  bunle = JSON.parse(mfs.readFileSync(bunldePath, 'utf-8'))
  console.log('new bundle')
})

const renderToString = (renderer, context) => new Promise((resolve, reject) => {
  renderer.renderToString(context, (err, html) => {
    if (err) reject(err);
    resolve(html)
  })
})

router.get('/(.*)', async ctx => {
  if (!bunle) {
    ctx.body = "webpack打包之后再访问"
    return 
  }
  const { data: clientManifest } = await axios.get('http://localhost:8080/vue-ssr-client-manifest.json')

  const renderer = createBundleRenderer(bunle, {
    runInNewContext: false,
    template: fs.readFileSync(
      path.resolve(__dirname, '../public/index-ssr.html'),
      'utf-8',
    ),
    clientManifest
  })


  try {
    const html = await renderToString(renderer, ctx)
    ctx.body = html;
  } catch (error) {
    console.log(error)
  }


})




module.exports = router